import { Injectable } from '@angular/core';
import { NoticeService } from '../notice-service';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
declare var Wechat, WeiboSDK;

@Injectable()
export class LoginPluginProvider {

  constructor(
    private noticService: NoticeService,
  ) {
    console.log('loin登录 LoginPluginProvider Provider');
  }

  Toast(str) {
    this.noticService.showNoticeByToast(1, str);
  }

  // 微信登录
  public loginByWechat() {
    let scope = "snsapi_userinfo";
    let state = "_" + (+new Date());
    return new Promise((resolve, reject) => {
      if (typeof (Wechat) === "undefined") {
        this.Toast("Wechat plugin is not installed.");
        reject();
        return false;
      }
      //检查是否安装了微信
      Wechat.isInstalled(function (installed) {
        if (installed) {
          Wechat.auth(scope, state, function (response) {
            resolve(response)
          }, function (reason) {
            alert(reason)
            this.Toast("微信登录失败");
          })
        } else {
          this.Toast("未检测到微信手机应用");
        }
      }, function (reason) {
        this.Toast("Failed: " + reason);
      });

    })
  }
  /**
   * 微博登录
   */
  public loginBySina() {
    return new Promise((resolve, reject) => {
      if (typeof (WeiboSDK) === "undefined") {
        this.Toast("WeiboSDK plugin is not installed.");
        reject();
        return false;
      }
          //检查是否安装了 微博
      WeiboSDK.checkClientInstalled(function () {
        WeiboSDK.ssoLogin(function (args) {
          // alert('access token is ' + args.access_token);
          // alert('userId is ' + args.userId);
          // alert('expires_time is ' + new Date(parseInt(args.expires_time)) + ' TimeStamp is ' + args.expires_time);
          resolve(args);
        }, function (reason) {
          reject(reason);
          this.Toast("微博登录失败");
        });
      }, function () {
        this.Toast("未检测到微博手机应用");
      });
    });
  }



}
